package models

import (
	"awesome-devops/boot"
	"gorm.io/gorm"
	"time"
)

const DEPLOY_ING = 1 //发布中
const DEPLOY_SUCCESS = 2
const DEPLOY_FAIL = 3

type Deploy struct {
	BaseModel
	Id            int       `json:"id"`
	ProjectId     int       `json:"project_id"`
	LastCommitId  string    `json:"last_commit_id"`
	CommitId      string    `json:"commit_id"`
	DeployComment string    `json:"deploy_comment"`
	Status        int       `json:"status"`
	RunTime       float64   `json:"run_time"`
	Log           string    `json:"log"`
	CreateTime    time.Time `json:"create_time"`
	UpdateTime    time.Time `json:"update_time"`
	StartAt       time.Time `json:"start_at"`
	EndAt         time.Time `json:"end_at"`
}

func (baseModel *Deploy) TableName() string {
	return "ops_deploy_log"
}
func (baseModel *Deploy) BeforeCreate(tx *gorm.DB) (err error) {
	baseModel.CreateTime = time.Now().Local()
	baseModel.UpdateTime = time.Now().Local()
	return tx.Error
}

func GetLastCommit(projectId int) (Deploy, error) {
	deploy := Deploy{}
	result := boot.GetDbConnection().Table(deploy.TableName()).
		Where("project_id", projectId).
		Where("delete_time=0").
		Where("status", DEPLOY_SUCCESS).
		Order("id desc").
		First(&deploy)
	if result.Error != nil {
		return deploy, result.Error
	}
	return deploy, nil
}
